import React, {useState, useEffect} from 'react';
import {Table, Button, Form, Space, message, Input as AntInput, Modal} from 'antd';
import {
    getStudentInfo,
    addStudent,
    deleteStudent,
    updateStudent,
    batchDeleteStudent,
    chooseClass
} from "../../api/student.js";
import StudentFormModal from "./component/StudentFormModal.jsx";
import ChooseModal from "./component/ChooseModal.jsx";

const StudentPage = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [editingStudent, setEditingStudent] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchKeyword, setSearchKeyword] = useState('');
    const [modalVisible, setModalVisible] = useState(false);
    const [chooseModalVisible, setChooseModalVisible] = useState(false);


    useEffect(() => {
        fetchStudents();
    }, []);

    const fetchStudents = async () => {
        setLoading(true);
        try {
            const res = await getStudentInfo(null);
            setData(res.data);
        } catch (error) {
            message.error('获取学生列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };
    const showChooseModal = (record) => {

        if (record.degree === "本科") {
            setEditingStudent(record);
            setChooseModalVisible(true);
        } else {
            message.warning("研究生不能选择班级");
        }

    };

    const onOk = async (values) => {
        setLoading(true);

        if (editingStudent) {
            const res = await chooseClass({
                studentId: values.id,
                classId: values.classId,
            });
            if (res.code === 200) {
                await fetchStudents();
                message.success('选择班级成功');
            } else {
                message.error("选择班级失败")
            }
        }
        setChooseModalVisible(false);
        setEditingStudent(null);
    }

    const showModal = (record) => {
        setEditingStudent(record);
        setModalVisible(true);
    };

    const handleOk = async (values) => {
        try {
            setLoading(true);

            if (editingStudent) {
                const res = await updateStudent({
                    id: editingStudent.id,
                    studentId: values.studentId,
                    academyId: values.academyId,
                    specialtyId: values.specialtyId,
                    classId: values.classId,
                    name: values.name,
                    gender: values.gender,
                    age: parseInt(values.age),
                    grade: String(values.grade).slice(-2),
                    degree: values.education
                });
                if (res.code === 200) {
                    await fetchStudents();
                    message.success('修改成功');
                } else {
                    message.error("修改失败")
                }
            } else {
                const res = await addStudent({
                    studentId: values.studentId,
                    academyId: values.academyId,
                    specialtyId: values.specialtyId,
                    classId: values.classId,
                    name: values.name,
                    gender: values.gender,
                    age: parseInt(values.age),
                    grade: String(values.grade).slice(-2),
                    degree: values.education
                });
                if (res.code === 200) {
                    await fetchStudents();
                    message.success('新增成功');
                } else {
                    message.error("新增失败");
                }
            }
            setLoading(false);
            setModalVisible(false);
            setEditingStudent(null);
        } catch (error) {
            message.error('操作失败，请重试');
            console.error(error);
            setLoading(false);
            setEditingStudent(null);
        }
    };
    const cancelStudentFormModal = () => {
        setModalVisible(false);
        setEditingStudent(null);
    }
    const cancelChooseModal = () => {
        setChooseModalVisible(false);
        setEditingStudent(null);
    }

    const deleteStudentById = async (id) => {
        try {
            setLoading(true);
            const res = await deleteStudent({id: id});
            if (res.code === 200) {
                await fetchStudents();
                message.success('删除成功');
            } else {
                message.error('删除失败');
            }
        } catch (error) {

            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const batchDeleteStudents = async () => {
        if (!selectedRowKeys.length) return;
        try {
            setLoading(true);
            const res = await batchDeleteStudent({ids: selectedRowKeys});
            if (res.code === 200) {
                await fetchStudents();
                setSelectedRowKeys([]);
                message.success('批量删除成功');
            } else {
                message.error('批量删除失败');
            }
        } catch (error) {
            message.error('批量删除失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (e) => {
        if (e.target.value === '') {
            fetchStudents();
        }
        setSearchKeyword(e.target.value);
    };

    const handleSearch = async () => {
        if (!searchKeyword.trim()) {
            message.warning('请输入搜索内容');
            return;
        }
        setLoading(true);
        try {
            const res = await getStudentInfo(searchKeyword);
            setData(res.data);
        } catch (error) {
            message.error('获取失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            render: (_, record, index) => index + 1,
            align: 'center',
            width: 60,
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
            align: 'center',
            width: 120,
        },
        {
            title: '学院',
            dataIndex: 'academyName',
            key: 'academyName',
            align: 'center',
            width: 120,
        },
        {
            title: '专业',
            dataIndex: 'specialtyName',
            key: 'specialtyName',
            align: 'center',
            width: 120,
        },
        {
            title: '班级',
            dataIndex: 'className',
            key: 'className',
            align: 'center',
            width: 120,
            render: (className) => className ?? '暂无',
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            width: 90,
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            width: 60,
            align: 'center',
            render: (text) => (text === 1 ? '男' : '女'),
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            width: 60,
            align: 'center'
        },
        {
            title: '年级',
            dataIndex: 'grade',
            key: 'grade',
            width: 60,
            align: 'center',
        },
        {
            title: '学历',
            dataIndex: 'degree',
            key: 'degree',
            width: 60,
            align: 'center'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => showChooseModal(record)}>选择班级</Button>
                    <Button type="link" onClick={() => showModal(record)}>编辑</Button>
                    <Button type="link" danger onClick={() => deleteStudentById(record.id)}>删除</Button>
                </Space>
            ),
        },
    ];

    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    return (
        <div style={{padding: 14}}>
            <div style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between',
                flexWrap: 'wrap',
                gap: 8
            }}>
                <Space>
                    <Button type="primary" onClick={() => setModalVisible(true)}>
                        新增学生
                    </Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={batchDeleteStudents}>
                        批量删除
                    </Button>
                </Space>

                <Space>
                    <AntInput.Search
                        placeholder="请输入学生名称"
                        value={searchKeyword}
                        onChange={handleInputChange}
                        onSearch={handleSearch}
                        style={{width: 250}}
                        allowClear
                    />
                </Space>
            </div>

            <Table
                rowKey="id"
                dataSource={data}
                columns={columns}
                rowSelection={rowSelection}
                pagination={{pageSize: 10}}
                loading={loading}
            />

            <StudentFormModal
                visible={modalVisible}
                onCancel={() => cancelStudentFormModal()}
                onOk={handleOk}
                editingStudent={editingStudent}
            />

            <ChooseModal
                visible={chooseModalVisible}
                onCancel={() => cancelChooseModal()}
                onOk={onOk}
                editingStudent={editingStudent}
            />
        </div>
    );
};

export default StudentPage;